<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试ProductType修复</title>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            max-width: 1000px; 
            margin: 0 auto; 
            padding: 20px; 
        }
        .test-section { 
            margin: 20px 0; 
            padding: 15px; 
            border: 1px solid #ddd; 
            border-radius: 5px; 
        }
        .success { border-color: #4caf50; background-color: #f8fff8; }
        .error { border-color: #f44336; background-color: #fff8f8; }
        .warning { border-color: #ff9800; background-color: #fffbf0; }
        .log { 
            background: #f5f5f5; 
            padding: 10px; 
            border-radius: 3px; 
            font-family: monospace; 
            white-space: pre-wrap; 
            max-height: 300px; 
            overflow-y: auto; 
        }
        button {
            background: #007cba;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover { background: #005a8b; }
    </style>
</head>
<body>
    <h1>ProductType 数据结构修复验证</h1>
    
    <div class="test-section">
        <h3>测试目标</h3>
        <p>验证产品类型数据在ProductList.vue中的显示是否正常，不再出现以下错误：</p>
        <code>Cannot read properties of undefined (reading 'displayName')</code>
    </div>
    
    <div class="test-section">
        <h3>测试步骤</h3>
        <button onclick="testProductTypesAPI()">1. 测试ProductType API</button>
        <button onclick="testDataStructure()">2. 测试数据结构</button>
        <button onclick="testSelectOptions()">3. 测试选择器选项生成</button>
        <button onclick="clearLogs()">清除日志</button>
    </div>
    
    <div class="test-section">
        <h3>测试结果</h3>
        <div id="results"></div>
    </div>
    
    <div class="test-section">
        <h3>控制台日志</h3>
        <div id="console-log" class="log"></div>
    </div>

    <script>
        const resultsDiv = document.getElementById('results');
        const logDiv = document.getElementById('console-log');
        
        // 捕获console.log并显示
        const originalLog = console.log;
        const originalError = console.error;
        const originalWarn = console.warn;
        
        function addToLog(type, ...args) {
            const timestamp = new Date().toLocaleTimeString();
            const message = args.map(arg => 
                typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)
            ).join(' ');
            logDiv.textContent += `[${timestamp}] ${type}: ${message}\n`;
            logDiv.scrollTop = logDiv.scrollHeight;
        }
        
        console.log = (...args) => {
            originalLog(...args);
            addToLog('LOG', ...args);
        };
        
        console.error = (...args) => {
            originalError(...args);
            addToLog('ERROR', ...args);
        };
        
        console.warn = (...args) => {
            originalWarn(...args);
            addToLog('WARN', ...args);
        };
        
        function addResult(type, title, content) {
            const div = document.createElement('div');
            div.className = `test-section ${type}`;
            div.innerHTML = `<h4>${title}</h4><p>${content}</p>`;
            resultsDiv.appendChild(div);
        }
        
        function clearLogs() {
            logDiv.textContent = '';
            resultsDiv.innerHTML = '';
        }
        
        async function testProductTypesAPI() {
            try {
                console.log('🧪 开始测试ProductType API...');
                
                const response = await fetch('/apis/content.halo.run/v1alpha1/product-types?page=0&size=10');
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const data = await response.json();
                console.log('📦 API响应数据:', data);
                
                if (data.items && data.items.length > 0) {
                    const firstItem = data.items[0];
                    console.log('🔍 第一个产品类型结构:', firstItem);
                    
                    const hasSpec = !!firstItem.spec;
                    const hasDisplayName = !!firstItem.spec?.displayName;
                    const hasMetadata = !!firstItem.metadata;
                    const hasName = !!firstItem.metadata?.name;
                    
                    console.log('✅ 数据结构检查:');
                    console.log('  - spec字段:', hasSpec);
                    console.log('  - spec.displayName:', hasDisplayName);
                    console.log('  - metadata字段:', hasMetadata);
                    console.log('  - metadata.name:', hasName);
                    
                    if (hasSpec && hasDisplayName && hasMetadata && hasName) {
                        addResult('success', 'API测试通过', 
                            `成功获取到${data.items.length}个产品类型，数据结构完整`);
                    } else {
                        addResult('error', 'API测试失败', 
                            '数据结构不完整，缺少必要字段');
                    }
                } else {
                    addResult('warning', 'API测试警告', '没有获取到产品类型数据');
                }
                
            } catch (error) {
                console.error('❌ API测试失败:', error);
                addResult('error', 'API测试失败', error.message);
            }
        }
        
        async function testDataStructure() {
            try {
                console.log('🧪 开始测试数据结构处理...');
                
                // 模拟ProductList.vue中的数据处理逻辑
                const response = await fetch('/apis/content.halo.run/v1alpha1/product-types?page=0&size=10');
                const data = await response.json();
                
                console.log('🏷️ 获取到的产品类型数据:', data);
                console.log('🏷️ 产品类型数组:', data.items);
                
                if (data.items && data.items.length > 0) {
                    console.log('🏷️ 第一个产品类型结构:', data.items[0]);
                    console.log('🏷️ 是否有spec字段:', !!data.items[0].spec);
                    console.log('🏷️ 是否有displayName:', !!data.items[0].spec?.displayName);
                    
                    addResult('success', '数据结构测试通过', 
                        '数据结构符合Extension格式要求');
                }
                
            } catch (error) {
                console.error('❌ 数据结构测试失败:', error);
                addResult('error', '数据结构测试失败', error.message);
            }
        }
        
        async function testSelectOptions() {
            try {
                console.log('🧪 开始测试选择器选项生成...');
                
                const response = await fetch('/apis/content.halo.run/v1alpha1/product-types?page=0&size=10');
                const data = await response.json();
                
                // 模拟ProductList.vue中的选项生成逻辑
                const productTypes = data.items || [];
                
                console.log('🎛️ 开始生成选择器选项...');
                
                const options = [
                    { label: '全部类型', value: '' },
                    ...productTypes.map((type) => {
                        const label = type.spec?.displayName || type.displayName || '未知类型';
                        const value = type.metadata?.name || type.name || '';
                        
                        console.log(`📋 生成选项: ${label} -> ${value}`);
                        
                        return { label, value };
                    })
                ];
                
                console.log('✅ 最终选项列表:', options);
                
                // 检查是否有未知类型
                const hasUnknownTypes = options.some(opt => opt.label === '未知类型');
                const hasEmptyValues = options.some(opt => opt.value === '' && opt.label !== '全部类型');
                
                if (!hasUnknownTypes && !hasEmptyValues) {
                    addResult('success', '选择器选项测试通过', 
                        `成功生成${options.length}个选项，无异常数据`);
                } else {
                    addResult('warning', '选择器选项有警告', 
                        `发现异常数据: 未知类型=${hasUnknownTypes}, 空值=${hasEmptyValues}`);
                }
                
            } catch (error) {
                console.error('❌ 选择器选项测试失败:', error);
                addResult('error', '选择器选项测试失败', error.message);
            }
        }
        
        // 页面加载完成后显示说明
        document.addEventListener('DOMContentLoaded', () => {
            console.log('🚀 ProductType数据结构修复验证页面已加载');
            console.log('📝 请点击测试按钮验证修复效果');
        });
    </script>
</body>
</html>